//
//  WCNHomeVC.m
//  WCN
//
//  Created by wsj2015 on 16/3/30.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNHomeVC.h"
#import "WCDrawBorderView.h"
#import "WCNHomeCenterView.h"
#import "WCNHomePatientView.h"
#import "Constants.h"
#import "WCNPatientVC.h"
#import "WCNPastPaientsVC.h"
#import "WCNPatientAndRecordVC.h"
#import "WCNOrdersVC.h"
#import "WCNPiccPatientListVC.h"
//#import "WCNNavigationController.h"
#import "MyAttributedStringBuilder.h"
#import "WCNHomeImageView.h"
#import "WCNHomeBtn.h"
#import <YTXAnimations/UIView+YTXAnimateCSS.h>
#import "WSJAnimationTool.h"
#import "WSJTwoLevelPicker.h"
#import "WCNMeetingHomePage.h"
#import "WCImageView +setImage.h"
#import "SDCycleScrollView.h"
#import "WCBannerModel.h"
#import "WCNNewsDetailVC.h"
#import "WCButtonForNoti.h"
#import "cwqMessageTypesVC.h"
#import "WCBPushToolByWsj.h"
#import "WCNotifyMessageListVC.h"


#define kNAV_HEIGHT 54

#define kHEAD_HEIGHT 0.2286 *(kScreenHeight -49 -64)
#define kPART_HEIGHT 0.2051 *(kScreenHeight -49 -64)
@interface WCNHomeVC ()<SDCycleScrollViewDelegate>


@property (nonatomic,  strong) UIImageView *headView;

@property (nonatomic,  strong) UIView *corePartView;

@property (nonatomic,  strong) UIView *patientView;

@property (nonatomic, assign)  NSInteger unread;;
@property (nonatomic,  strong) UILabel *notiLabe;
@property (nonatomic,  strong) UIView *navCover;

@property (nonatomic,  strong) SDCycleScrollView *banner;

@property (nonatomic,  strong) NSMutableArray *bannerArray;

@property (nonatomic, strong) WCButtonForNoti *notiBtn;


@end

@implementation WCNHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self prepareBanerData];
   
  
  
}

- (instancetype)init
{
    self = [super init];
    if (self) {
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUnreadChatNunmber:) name:achatUnreadNumberNotification object:nil];
        self.unread = 0;
       
    }
    return self;
}


- (void)updateUnreadChatNunmber:(NSNotification *)userInfor
{
    NSDictionary *unreadDict = userInfor.userInfo;
    self.unread = [unreadDict[@"unread_aChat"] integerValue];

}
- (void)setUnread:(NSInteger)unread{
    _unread = unread;
    self.notiLabe.text = [NSString stringWithFormat:@"%i",unread];
    if (unread==0) {
        self.notiLabe.hidden =YES;
    }else{
        self.notiLabe.hidden =NO;
        
    }
    
 
}


- (void)loadView{
    [super loadView];
    
    //    [self.navigationController.navigationBar setHidden:YES];
 
}
#pragma mark -铃铛按钮
- (WCButtonForNoti *)notiBtn{
    if (_notiBtn ==nil) {
        _notiBtn =[[WCButtonForNoti alloc] initWithFrame:CGRectMake(kScreenWidth -35 -20, 24, 28, 22) withBtnImage:@"铃铛_samll"];
        _notiBtn.notices = 0;
        weakSelf_define;
        _notiBtn.pressBlock = ^(){
            WCNotifyMessageListVC *vc =[[WCNotifyMessageListVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
    }
    return _notiBtn;
    
}
#pragma mark -当行覆盖视图
- (UIView *)navCover{
    if (!_navCover) {
        _navCover = [UIView new];
        _navCover.backgroundColor  = HexRGB_WSJ(252, 79, 72);
        _navCover.frame = CGRectMake(0, -20, kScreenWidth, kNAV_HEIGHT+20);
        [self.navigationController.navigationBar addSubview:_navCover];
        
        UIImageView *headView =[UIImageView new];
        headView.frame = CGRectMake(12, 4 +20, 46, 46);
        headView.tag = 900;
        headView.layer.cornerRadius = 46/2;
        headView.layer.masksToBounds = YES;
        headView.layer.borderColor = [UIColor whiteColor].CGColor;
        headView.layer.borderWidth = 2;
        NSString *str  =WCN_ACCOUT().avatarFileId;
        [headView wsjSetImageWithUrl:str withPlaceImageName:@"Nurse_default"];
        [_navCover addSubview:headView];
        
        
        CGFloat space = CGRectGetMaxX(headView.frame) +21;
       
        
        UILabel *hospitalLabel =[UILabel new];
        hospitalLabel.frame = CGRectMake(space, 8 +20, kScreenWidth -space-8-30, 20);
        hospitalLabel.font = [UIFont boldSystemFontOfSize:14];
        hospitalLabel.textColor = [UIColor whiteColor];
        hospitalLabel.text = [[[WCDefaultManager shareMg] account] hospitalName];
        hospitalLabel.tag = 901;
        [_navCover addSubview:hospitalLabel];
        
        UILabel *nameLable =[UILabel new];
        nameLable.frame = CGRectMake(space, CGRectGetMaxY(hospitalLabel.frame), kScreenWidth -space-8-8, 20);
        nameLable.font = [UIFont systemFontOfSize:12];
        nameLable.textColor = [UIColor whiteColor];
       
        nameLable.tag = 902;
        [_navCover addSubview:nameLable];
        MyAttributedStringBuilder *builder = nil;
        NSString *name =[[[WCDefaultManager shareMg] account] name];
        NSString *jobTitle =[[[WCDefaultManager shareMg] account] jobTitle];
        if (jobTitle) {
            builder = [[MyAttributedStringBuilder alloc] initWithString:[NSString stringWithFormat:@"%@  %@",name,jobTitle]];
            [builder includeString:jobTitle all:YES].textColor = [UIColor whiteColor];
            
        }
        nameLable.attributedText = builder.commit;
      
        UIButton *btn;
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 30, 20, 0)];
        self.notiBtn.frame = CGRectMake(kScreenWidth -18-6, 3 +20, 18, 18);
    
        
        self.notiBtn.notices = 10;
        self.notiBtn.backgroundColor = [UIColor clearColor];
        self.notiBtn.notiR = 6;
        self.notiBtn.notiTextClor = [UIColor redColor];
        self.notiBtn.notiBackroundColor =[UIColor whiteColor];
        [_navCover addSubview:self.notiBtn];
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [_navCover addGestureRecognizer:tap];
        
        
    }
    return _navCover;
}

#pragma mark -进入消息列表
- (void)tapAction:(UIGestureRecognizer *)g{
    if ([g locationInView:self.navCover].x>=kScreenWidth-40){
        WCNotifyMessageListVC *vc =[[WCNotifyMessageListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
  
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    CGRect rect = self.navigationController.navigationBar.frame ;
    rect.size.height =44;
    rect.origin.y =20;
    self.navigationController.navigationBar.frame = rect;
//    self.navCover.hidden = YES;
    
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [UIView animateWithDuration:.35f animations:^{
        self.navCover.alpha =0;
        self.navCover.hidden = YES;
         self.navigationController.navigationBar.frame = rect;
        
    }];
   
   
 
  

}

#pragma mark -请求站内消息未读数
- (void)getNotifyMessageCount{
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimpleInImageView:self.notiBtn];
    //    "targetId": 86,
    //    "targetType": 1
    NSInteger targetId =[[[[WCDefaultManager shareMg] account] stringId] integerValue];
    NSDictionary *params =@{@"targetId":@(targetId),@"targetType":@(1)};
    weakSelf_define;
    [[WCNetworkAccessManager sharedMg] POST:kNotifyMessageCount parameters:params success:^(NSDictionary * responseObject) {
        NSInteger num =[responseObject[@"data"] integerValue];
        if (num && num>0) {
            [WCBPushToolByWsj saveNewBadge:num];
            weakSelf.notiBtn.notices = num;
        }else{
            [WCBPushToolByWsj saveNewBadge:0];
            weakSelf.notiBtn.notices = 0;
            
        }
        
        
    } failure:nil netError:nil always:^{
        [hud hide:YES];
        
    }];
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    
    UILabel *hospitalLabel = [self.headView viewWithTag:200];
    UILabel *nameLabel = [self.headView viewWithTag:300];
    
    [hospitalLabel  ytx_flipInXAnimtionWithDurationTime:1];
    [nameLabel  ytx_rubberBandAnimtionWithDurationTime:1];
    
    CGRect rect = self.navigationController.navigationBar.frame ;
    rect.size.height =kNAV_HEIGHT;
    
    self.navigationController.navigationBar.frame = rect;
//    self.navCover.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    
    [UIView animateWithDuration:.35f animations:^{
        self.navCover.alpha =1;
         self.navCover.hidden = NO;
         self.navigationController.navigationBar.frame = rect;
    }];
    UIImageView *head =[self.navCover viewWithTag:900];
    [head ytx_flipInYAnimtionWithDurationTime:2.0f];
    [self getNotifyMessageCount];
}
- (void)dealloc{
 
}
- (NSMutableArray *)bannerArray{
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
    
}

- (UIImageView *)headView{
    if (!_headView) {
        _headView = [UIImageView new];
        _headView.backgroundColor = kAppBg;
        _headView.image =[UIImage imageNamed:@"home_bgImage"];
        UILabel *hospitalLabel =[UILabel new];
        hospitalLabel.font = [UIFont boldSystemFontOfSize:17];
        hospitalLabel.textAlignment = NSTextAlignmentCenter;
//        NSString *ho = [[[WCDefaultManager shareMg] account] hospitalName];
        hospitalLabel.text = [[[WCDefaultManager shareMg] account] hospitalName];
        hospitalLabel.textColor = [UIColor redColor];
        hospitalLabel.tag = 200;
        hospitalLabel.frame = CGRectMake(10, kHEAD_HEIGHT/2 -30, kScreenWidth -20, 30);
        [_headView addSubview:hospitalLabel];
        UILabel *nurseNameLabel =[UILabel new];
        nurseNameLabel.font =[UIFont systemFontOfSize:14];
        nurseNameLabel.textAlignment = NSTextAlignmentCenter;
        nurseNameLabel.frame = CGRectMake(10, kHEAD_HEIGHT/2+10, kScreenWidth- 20, 24);
        nurseNameLabel.tag = 300;
        MyAttributedStringBuilder *builder = nil;
        NSString *name =[[[WCDefaultManager shareMg] account] name];
        NSString *jobTitle =[[[WCDefaultManager shareMg] account] jobTitle];
        if (jobTitle) {
            builder = [[MyAttributedStringBuilder alloc] initWithString:[NSString stringWithFormat:@"%@  %@",name,jobTitle]];
            [builder includeString:jobTitle all:YES].textColor = [UIColor redColor];

        }
                nurseNameLabel.attributedText = builder.commit;
        [_headView addSubview:nurseNameLabel];
        
    }
    return _headView;
}
#pragma mark -中间区域
- (UIView *)corePartView{
    if (!_corePartView) {
         _corePartView =  [WCNHomeCenterView new];
        _corePartView.backgroundColor = [UIColor whiteColor];
        CGFloat x ;
        CGFloat y ;
        CGFloat space = 1;
        CGFloat w = kScreenWidth /2-1;
        CGFloat h = kPART_HEIGHT-1;
        for (int i = 0; i<4; i++) {
            if (i<2) {
                x = (w +space)* i;
                y = 0;
            }else{
                x = (w +space) *(i -2);
                y = h;
            }
            NSArray *titleArray =@[@"随访患者",@"我的订单",@"视频会议",@"过往患者"];
            NSArray *imageArray =@[@"出诊名单_home",@"我的订单_home",@"随访患者_home",@"过往患者_home"];
            WCNHomeImageView *imageView =[WCNHomeImageView new];
            imageView.frame = CGRectMake(x, y, w, h);
//            imageView.backgroundColor = [UIColor grayColor];
            imageView.userInteractionEnabled = YES;
            imageView.tag = 1000+i;
            UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(partTapAction:)];
            [imageView addGestureRecognizer:tap];
            [_corePartView addSubview:imageView];
            imageView.title= titleArray[i];
            imageView.image =[UIImage imageNamed:imageArray[i]];
            if (i==1) {
                UILabel *label =[UILabel new];
                CGFloat labelW = 18;
                label.backgroundColor = [UIColor redColor];
                label.layer.cornerRadius = labelW/2;
                label.layer.masksToBounds = YES;
                label.textColor = [UIColor whiteColor];
                label.textAlignment = NSTextAlignmentCenter;
                label.adjustsFontSizeToFitWidth = YES;
                label.frame = CGRectMake( imageView.imageView.bounds.size.width -labelW , 0, labelW, labelW);
               
                [imageView.imageView addSubview:label];
                label.hidden = YES;
                self.notiLabe = label;
                
            }
        }

    }
    return _corePartView;
}
#pragma mark -下面区域
- (UIView *)patientView{
    if (!_patientView) {
       
        _patientView =  [WCNHomePatientView new];
        _patientView.backgroundColor = [UIColor whiteColor];
               CGFloat w =kScreenWidth /2;
        UILabel *label =[UILabel new];
        label.text = @"住院患者";
        label.font = [UIFont boldSystemFontOfSize:16];
        CGFloat topSapce;
        if (kScreenWidth ==320) {
            
            topSapce = 6;
        }else if(kScreenWidth == 375){
            
            topSapce = 15;
        }else if (kScreenWidth > 400){
            
            topSapce = 18;
        }
        label.frame = CGRectMake(20,topSapce, 200, 38);
        [_patientView addSubview:label];
        CGFloat h = 0.5528 *2*kPART_HEIGHT /2;
        
        CGFloat y  =h +1;
        CGFloat space =1;
        NSArray *titleArray =@[@"伤口患者",@"PICC患者"];
        NSArray *iamgeArray =@[@"伤口患者_home_btn",@"PICC_home_btn"];
        for (int i = 0; i<2; i++) {
            WCNHomeBtn *btn =[WCNHomeBtn buttonWithType:UIButtonTypeCustom];
            [btn addTarget:self action:@selector(pateintBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//            btn.backgroundColor = [UIColor redColor];
            btn.frame = CGRectMake((w +space)*i , y, w, h);
//            [btn setTitle:titleArray[i] forState:UIControlStateNormal];
            btn.title = titleArray[i];
            btn.leftImage =[UIImage imageNamed:iamgeArray[i]];
            btn.tag = 2000+i;
            
            [_patientView addSubview:btn];
            
        }
        
     
    }
    return _patientView;
}

- (void)setupUI{
  
    self.view.backgroundColor = kAppBg;
   
    [self.view addSubview:self.banner];
    [self.view addSubview:self.corePartView];
    [self.view addSubview:self.patientView];
//    self.headView.frame = CGRectMake(0, kNAV_HEIGHT -44, kScreenWidth, kHEAD_HEIGHT);
//    self.banner.frame =CGRectMake(0, kNAV_HEIGHT -44, kScreenWidth, kHEAD_HEIGHT);
    self.corePartView.frame = CGRectMake(0, CGRectGetMaxY(self.banner.frame)+4, kScreenWidth, 2*kPART_HEIGHT);
//    self.banner.backgroundColor = [UIColor greenColor];
    
    self.patientView.frame = CGRectMake(0,CGRectGetMaxY(self.corePartView.frame)+8, kScreenWidth, 0.5528 *self.corePartView.bounds.size.height);
    
    [self.corePartView  ytx_zoomInDownAnimtionWithDurationTime:1];
    [self.patientView  ytx_zoomInRightAnimtionWithDurationTime:1];
}
#pragma mark -轮播视图
- (SDCycleScrollView *)banner{
    if (!_banner) {
        _banner = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kNAV_HEIGHT -44, kScreenWidth, kHEAD_HEIGHT) imageURLsGroup:nil];
        
        _banner.delegate =self;
        _banner.pageControlDotSize =CGSizeMake(kOnePX, kOnePX);
        _banner.dotColor = [UIColor whiteColor];
        _banner.autoScrollTimeInterval =5.f;
    }
     return _banner;
}
- (void)pateintBtnAction:(UIButton *)btn{
    if (btn.tag ==2000) {
        [self.navigationController pushViewController:[WCNPatientVC new] animated:YES ];
    }else{
        [self.navigationController pushViewController:[WCNPiccPatientListVC new] animated:YES ];

    }
    
}
#pragma mark -按钮事件
- (void)partTapAction:(UITapGestureRecognizer *)tap{
    
    [tap.view ytx_rubberBandAnimtionWithDurationTime:1];
    switch (tap.view.tag -1000) {
        case 0:
            [self.navigationController pushViewController:[WCNPatientAndRecordVC new] animated:YES];
            
            break;
        case 1:
            [self.navigationController pushViewController:[WCNOrdersVC new] animated:YES];
            
            break;
        case 2:
           
            [self.navigationController pushViewController: [WCNMeetingHomePage new] animated:YES];
            break;
        case 3:
             [self.navigationController pushViewController:[WCNPastPaientsVC new] animated:YES ];
            break;
            
        default:
            break;
    }
    
}

#pragma mark -点进轮播的方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    WCBannerModel *model =_bannerArray[index];
    NSInteger newsId =[model.bannerNews integerValue];
    [self jumpToNewsPageWithNewsId:newsId];
    
}
#pragma -mark 请求轮播数据
- (void)prepareBanerData
{
    
    NSMutableArray *imageUrlArray =[NSMutableArray new];
    NSString *bathUrl =[UIImageView getimageUrlForMedia];
    defineWeakSelf;
    [[WCNetworkAccessManager sharedMg] GET:kBanner_part  parameters:nil success:^(NSDictionary *responseObject) {
       
        for (NSDictionary *dataDict in responseObject[@"data"]) {
            WCBannerModel *model =[[WCBannerModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDict];
//            [bannerArray addObject:model];
            [weakSelf.bannerArray addObject:model];
            NSString *urlStr =[NSString stringWithFormat:@"%@%@",bathUrl,model.bannerImage];
            [imageUrlArray addObject:[NSURL URLWithString:urlStr]];
            
        }
        weakSelf.banner.imageURLsGroup =[NSArray arrayWithArray:imageUrlArray];
        
    } failure:nil netError:nil always:nil];
    
    
    
}
#pragma -mark 跳进网页的处理方法
- (void)jumpToNewsPageWithNewsId:(NSInteger)newsId
{
    
    Account *account =[[WCDefaultManager shareMg] account];
    NSString * patientId = account.stringId;
    
    NSString *name = account.name;
   
    
    
    NSString *urlStr =[NSString stringWithFormat:@"%@?newsId=%i&commentby=patient_%i&commentbyName=%@",kNewsDetail_url,newsId,[patientId integerValue],name];
    NSString * urlStrCode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlStr,NULL,NULL,kCFStringEncodingUTF8));
    WCNNewsDetailVC *vc =[[WCNNewsDetailVC alloc] init];
    vc.url =[NSURL URLWithString:urlStrCode];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
@end
